# Clean up
rm(list = ls())

# Set working directory; please set your own here
setwd("~/Dropbox/Fragmentation/fragmentation_replication_bjps/")

library(tidyverse)
library(readxl)

# Import data with main analyses
data <- read.dta("Results/analyses_final.dta")

# Defining line breaks in the type of outcome
levels(data$outcome_type) <- gsub("\\n", "\n", levels(data$outcome_type))

# Fixing levels in outcome and outcome_type variables
table(data$Outcome)
data$Outcome[data$Outcome == "Summary\\nmeasures (PCA)"] <- "Summary measures (PCA)"
data$Outcome[data$Outcome == "Repr underpriviliged\\ngroups (PCA)"] <- "Repr underpriviliged groups (PCA)"

table(data$outcome_type)
data$outcome_type[data$outcome_type == "Summary\\nmeasures"] <- "Summary\nmeasures"
data$outcome_type[data$outcome_type == "Descriptive\\nrepr of women"] <- "Descriptive\nrepr of women"
data$outcome_type[data$outcome_type == "Repr underpriviliged\\ngroups"] <- "Repr underpriviliged\ngroups"
data$outcome_type[data$outcome_type == "Other\\noutcomes"] <- "Other\noutcomes"

# Creating a variable to order the plot by
data$order_outcome <- 1
data$order_outcome[data$outcome_type == "Summary\nmeasures"] <- 0
data$order_outcome[data$outcome_type == "Other\noutcomes"] <- 2

# Make the plot
highthresholds_plot <- data %>%
  # mutate(order = ifelse(Instruments == 0, 0, 1)) %>%
  filter(Sample == "Threshold above median (4% of the vote)") %>%
  filter(FE == "None") %>%
  #filter(outcome_type != "Summary measures") %>%
  mutate(order = ifelse(Model == "OLS", 0, 1)) %>%
  mutate(Model = fct_reorder(Model, order)) %>%
  mutate(Outcome = fct_reorder(Outcome, pca)) %>%
  mutate(outcome_type = fct_reorder(outcome_type, order_outcome)) %>%
  mutate(inst = fct_reorder(inst, Instruments)) %>%
  mutate(order_ids = ifelse(id == "Means comparison", 0, 1)) %>%
  mutate(id = fct_reorder(id, order_ids)) %>%
  ggplot(aes(Outcome, Effect, color = factor(pca), show.legend = FALSE)) + 
  geom_hline(aes(yintercept = 0), linetype = 2) + 
  coord_flip(ylim = c(-1, 1)) + 
  geom_linerange(aes(ymin = ci_lower, ymax = ci_upper), position = position_dodge(width = 0.75) ) + 
  geom_point(size = 1, position = position_dodge(width = 0.75) ) + 
  facet_grid(rows = vars(outcome_type),
             scales = "free_y") + 
  #facet_grid(cols = vars(A), labeller = label_both)
  theme_minimal(base_size = 9) +
  theme(legend.position = "none",
        panel.background = element_rect(fill = NA, color = "black")) +
  scale_color_manual(values = c("black", "blue")) +
  ylab(" ") + 
  xlab("") 
highthresholds_plot

# Save the plot
ggsave("Plots/figc1.png", plot = highthresholds_plot, width = 35, height = 25, units = "cm") 